package com.bnq.logc.printer

import android.util.Log
import com.bnq.logc.LogcManager
import com.bnq.logc.config.LogcConfig
import com.bnq.logc.utils.DateUtil
import java.io.File
import java.io.FileWriter

class IOLogcPrinter(path:String) : LogcPrinter {
    private val logPath= File(path)//File(context.getExternalFilesDir(null),"log")
    private val logFile = File(logPath,"${DateUtil.formatDateTime(System.currentTimeMillis(),pattern = "yyyy-MM-dd")}.log")

    private fun getFile(): File {
        if(!logPath.exists()){
            logPath.mkdirs()
        }
        if(!logFile.exists()){
            val success = logFile.createNewFile()
            if(!success && LogcManager.getConfig().mIsDebug){
                Log.e("Logc","创建本地储存log文件失败：${logFile.absolutePath}")
            }
        }
        return logFile
    }

    override fun isEnabled(): Boolean = LogcManager.getConfig().mLogWriteModeConfig.isIO()

    override fun print(message: String) {
        try{
            FileWriter(getFile(),true).use { out ->
                out.write(message)
                out.flush()
            }
        }catch (e:Exception){
            e.printStackTrace()
            if(LogcManager.getConfig().mIsDebug){
                Log.e("Logc","写本地log失败：${logFile.absolutePath}")
                throw e
            }
        }
    }
}